package com.zxy.service;

import com.zxy.util.LogBack;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

@Service
public class ThreadHandle implements Runnable {

    static final Logger logger = LoggerFactory.getLogger( ThreadHandle.class);

    @Autowired
    OperateService operateService;

    private boolean canRun = true;

    public ThreadHandle(){
        System.out.println(" -------------------- init ThreadHandle -------------- ");
    }

    public boolean isWork(){
       return canRun ;
    }

    public void startWork(){
        canRun = true;
    }

    public void stopWork(){
        canRun = false;
    }

    public void run(){
        // 监听指定的端口
        /*try{
            int port = 55533;
            ServerSocket server = new ServerSocket(port);
            // server将一直等待连接的到来
            System.out.println("server将一直等待连接的到来");
            Socket socket = server.accept();
            // 建立好连接后，从socket中获取输入流，并建立缓冲区进行读取
            InputStream inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            int len;
            StringBuilder sb = new StringBuilder();
            while ((len = inputStream.read(bytes)) != -1) {
                //注意指定编码格式，发送方和接收方一定要统一，建议使用UTF-8
                sb.append(new String(bytes, 0, len,"UTF-8"));
            }
            System.out.println("get message from client: " + sb);
            inputStream.close();
            socket.close();
            server.close();
        }catch (Exception e){
            e.printStackTrace();
        }*/
        logger.info( "---------------------ThreadHandle----------------------");
        try{
            //while( true ){
                while( canRun ){
                    //logger.debug(" ThreadHandle run ");
                    //System.out.println(" -------------------- ThreadHandle run -------------- ");
                    logger.debug("------------------ThreadHandle");
                    operateService.doThing();
                    Thread.sleep(5 * 1000);
                }

           // }
        }catch (Exception e){
            e.printStackTrace();
        }


    }
}
